import { expect } from '@jest/globals';
import path from 'path';

import { initExecuteCommand, runHvigorAsync } from '../../../common/common';
import { commonFileOperation } from '../../../plugins/common-fun';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  IsEnable,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType, SignType,
} from '../../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../../plugins/task-builder/test-case';
import { TestTaskOption } from '../../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API11,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility
  }
};

const taskConfig: TestTaskOption = {
  caseLevel: CaseLevel.L2,
  sign: SignType.NoSign,
  ohpmInstall: IsEnable.DisAble,
};

const testFun: TestCaseFun = async (project, taskConfig, record) => {
  const projectRoot = project.projectRootPath();

  // 修改 工程目录下的 hvigorfile.ts
  await commonFileOperation(path.resolve(projectRoot, 'hvigorfile.ts'), async (buffer) => {
    const content = buffer.toString().replace('plugins:[]','plugins:[customPlugin()]');
    return `import { HvigorPlugin, HvigorNode } from \'@ohos/hvigor\'; \n` +
      `${content} ` +
      '// 实现自定义插件\n' +
      'function customPlugin(): HvigorPlugin {\n' +
      '    return {\n' +
      '        pluginId: \'customPlugin\',\n' +
      '        apply(node: HvigorNode) {\n' +
      '            // 插件主体\n' +
      '            console.log(\'hello customPlugin!\');\n' +
      '        }\n' +
      '    }\n' +
      '}';
  });

  const commands = initExecuteCommand({
    tasks: '--sync'
  });

  const result = await runHvigorAsync(projectRoot, commands, undefined, '@ohos/hvigor/bin/hvigor');
  record.addStep('step', result);

  expect(result.stdout).toContain('hello customPlugin!');
  expect(result.stdout).toContain('Finished :entry:init...');
  expect(result.stdout).toContain('Finished ::init...');
};

TestCaseBuilder.builder()
  .caseName('custom Plugin 01')
  .description('custom plugin: HelloWorld')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(taskConfig)
  .testFun(testFun)
  .load();
